﻿using System;
using System.Security.Cryptography;
using AutoMapper;
using MathNet.Numerics.Distributions;
using MD5Hash;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.VisualBasic;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using SqlSugar;
using WebApplication1.API返回类;
using WebApplication1.DTO;
using WebApplication1.Models.RBAC;
using WebApplication1.Models.商品信息;
using static WebApplication1.Controllers.Method;

namespace WebApplication1.Controllers
{
    /// <summary>
    /// API商品控制器
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class GoodsController : ControllerBase
    {
        private readonly ISqlSugarClient _db;
        private readonly IMapper mapper;

        public GoodsController(SqlSugar.ISqlSugarClient db,IMapper mapper)
        {
            this._db = db;
            this.mapper = mapper;
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="name">用户名称</param>
        /// <param name="pwd">用户密码</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<APIResult<UserDto>> Login(string name,string pwd)
        {

            //联表查询
            var linq = _db.Queryable<UserModel>().First(o => o.UserName == name);
            if(linq==null)
            {
                return APIResult<UserDto>.Fail("用户不存在");
            }
            var pwd2 = pwd.GetMD5();
            if(linq.UserPwd!=pwd2)
            {
                return APIResult<UserDto>.Fail("密码错误");
            }
            UserDto dto = new UserDto() { 
                RoleName=linq.RoleName,
                UserName=linq.UserName,
            };

            return  APIResult<UserDto>.Success("登陆成功", dto);
        }

        /// <summary>
        /// 查询商品信息
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public APIPing<GoodDto> GetGoodAll(int? id,int PageIndex=1, int PageSize=10)
        {
            var list = _db.Queryable<GoodsModel>()
                         .LeftJoin<GoodNameModel>((a, b) => a.NId == b.NId)//多个条件用&&
                         .Where(a => a.IsDelete == false)
                         .Select((a, b) => new GoodDto
                         {
                             RId = a.RId,
                             NId = a.NId,
                             NName = b.NName,
                             GBatch = a.GBatch,
                             GDay = a.GDay,
                             GGeneration = a.GGeneration,
                             GCompany = a.GCompany,
                             GInformation = a.GInformation,
                             GImg = a.GImg,
                             ProductImg=a.ProductImg,
                             IsDelete = a.IsDelete,
                         });
            if(id!=null)
            {
                list = list.Where(a=>a.NId==id);
            }
            int CountList = list.Count();
            return new APIPing<GoodDto>() {
                Code = APIEnum.成功,
                Message = "查询商品信息成功",
                CountList = CountList,
                PageCount = (int)Math.Ceiling((CountList*1.0)/PageSize),
                PageData = list.OrderByDescending(a => a.RId).Skip((PageIndex - 1) * PageSize).Take(PageSize).ToList(),
            };
        }

        /// <summary>
        /// 导出
        /// </summary>
        /// <param name="PageIndex"></param>
        /// <param name="PageSize"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult ExportFile(int PageIndex,int PageSize)
        {
            var list = _db.Queryable<GoodsModel>()
                            .LeftJoin<GoodNameModel>((a, b) => a.NId == b.NId)//多个条件用&&
                            .Where(a => a.IsDelete == false)
                            .Select((a, b) => new GoodDto
                            {
                                RId = a.RId,
                                NId = a.NId,
                                NName = b.NName,
                                GBatch = a.GBatch,
                                GDay = a.GDay,
                                GGeneration = a.GGeneration,
                                GCompany = a.GCompany,
                                GInformation = a.GInformation,
                                ProductImg = a.ProductImg,
                            });
            int CountList = list.Count();
            int PageCount = (int)Math.Ceiling((CountList * 1.0) / PageSize);
            list = list.OrderByDescending(a => a.RId).Skip((PageIndex - 1) * PageSize).Take(PageSize);
            IWorkbook b = new XSSFWorkbook();
            ISheet s = b.CreateSheet();
            IRow r1 = s.CreateRow(0);//创建第一行
            r1.CreateCell(0).SetCellValue("序号");
            r1.CreateCell(1).SetCellValue("商品名称");
            r1.CreateCell(2).SetCellValue("生产批次");
            r1.CreateCell(3).SetCellValue("保质期(天)");
            r1.CreateCell(4).SetCellValue("生产许可证号");
            r1.CreateCell(5).SetCellValue("生产企业");
            r1.CreateCell(6).SetCellValue("信息完善度");
            r1.CreateCell(7).SetCellValue("商品图片");
            int index = 1;
            foreach(var i in list.ToList())
            {
                IRow row2 = s.CreateRow(index);
                row2.CreateCell(0).SetCellValue(i.RId);
                row2.CreateCell(1).SetCellValue(i.NName);
                row2.CreateCell(2).SetCellValue(i.GBatch);
                row2.CreateCell(3).SetCellValue(i.GDay);
                row2.CreateCell(4).SetCellValue(i.GGeneration);
                row2.CreateCell(5).SetCellValue(i.GCompany);
                row2.CreateCell(6).SetCellValue(i.GInformation);
                row2.CreateCell(7).SetCellValue(i.ProductImg);
                index++;
            }
            byte[] arr = null;
            string f = new FileExtensionContentTypeProvider().Mappings[".xlsx"];
            string t = "商品信息.xlsx";
            using (MemoryStream ms = new MemoryStream())
            {
                b.Write(ms);
                arr = ms.ToArray();
            }
            return File(arr, f, t);
        }


        /// <summary>
        /// 查询商品名称信息
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public APIResult<List<GoodNameModel>> GetGoodNameAll()
        {
            var list = _db.Queryable<GoodNameModel>();

            return new APIResult<List<GoodNameModel>>()
            {
                Code = APIEnum.成功,
                Message = "查询商品信息成功",
                Data =list.ToList(),
            };
        }

        /// <summary>
        /// 添加商品信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public APIResult<int> CreateGood(CreateGoodDto g)
        {
            GoodsModel model = mapper.Map<GoodsModel>(g);
            model.CreateTime = DateTime.Now;
            int r = _db.Insertable(model).ExecuteReturnIdentity();
            if(r>0)
            {
                return APIResult<int>.Success("创建商铺数据成功",r);
            }
            else
            {
                return APIResult<int>.Fail("创建商铺数据失败");
            }
            
        }

        /// <summary>
        /// 逻辑删除商品信息
        /// </summary>
        /// <returns></returns>
        [HttpPut]
        public APIResult<int> DeleteGood(int id)
        {
            GoodsModel model = _db.Queryable<GoodsModel>().First(x=>x.RId==id);
            if(model==null)
            {
                return APIResult<int>.Fail("您要删除的商品信息不存在");
            }
            model.IsDelete = true;
            var r = _db.Updateable(model).ExecuteCommand();//实体有多少列更新多少列
            if (r > 0)
            {
                return APIResult<int>.Success("删除商品信息成功", r);
            }
            else
            {
                return APIResult<int>.Fail("删除商品信息失败");
            }

        }

        /// <summary>
        /// 修改商品信息
        /// </summary>
        /// <returns></returns>
        [HttpPut]
        public APIResult<int> UpdateGood(CreateGoodDto g)
        {
            var goods = _db.Queryable<GoodsModel>().First(x => x.RId == g.RId);
            if (goods == null)
            {
                return APIResult<int>.Fail("您要修改的商品信息不存在");
            }
            GoodsModel model = mapper.Map<GoodsModel>(g);
            model.UpdateTime = DateTime.Now;
            var r = _db.Updateable(model).ExecuteCommand();//实体有多少列更新多少列
            if (r > 0)
            {
                return APIResult<int>.Success("修改商品信息成功", r);
            }
            else
            {
                return APIResult<int>.Fail("修改商品信息失败");
            }

        }

        /// <summary>
        /// 批量删除商品信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public APIResult<int> UpdateGoodAll(string id)
        {
            List<int> idlist = id.Split(',').Select(x=>(Convert.ToInt32(x))).ToList();
            int r = 0;
            foreach (var i in idlist)
            {
                r = _db.Updateable<GoodsModel>()
                .SetColumns(it => it.IsDelete == true)//SetColumns是可以叠加的 写2个就2个字段赋值
                .Where(it => it.RId == i)
                .ExecuteCommand();
            }
            if (r > 0)
            {
                return APIResult<int>.Success("批量删除商品信息成功", r);
            }
            else
            {
                return APIResult<int>.Fail("批量删除商品信息失败");
            }
        }
    }
    
}
